<template>
  <div class="knowledge-container">
    <h3 class="knowledge-title">专业知识系统</h3>
    <el-table border :data="list" style="width: 100%" max-height="400px">
      <el-table-column prop="original_filename" label="文件名" />
      <el-table-column prop="file_size" label="文件大小" />
      <el-table-column prop="upload_time" label="更新时间" />
      <el-table-column prop="status_display" label="状态" />
      <!-- 操作 -->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleDownload(scope.row)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getData, postData } from '@/service/getData';
import axios from 'axios';
export default {
  data() {
    return {
      activeName: '专业知识系统',
      list: [],
    };
  },
  mounted() {
    // 刷新列表
    this.getInfo();
  },
  methods: {
    getInfo() {
      getData('api/bjdt_doc/documents/', {}, 'get')
        .then((res) => {
          this.list = res.data;
          console.log(res);
        })
        .catch((e) => {})
        .finally((v) => {});
    },
    handleDownload(row) {
      // 跳转新开页面 下载数据
      window.open(`/api/bjdt_doc/download-doc/?file_id=${row.document_id}`);
    },
  },
};

// 下载方法（blob）
const downloadWithAxios = async (fileId) => {
  try {
    const token = localStorage.getItem('token');
    const response = await axios({
      method: 'GET',
      url: `/api/download-doc/?fileId=${fileId}`,
      headers: {
        Authorization: `Token ${token}`,
      },
      responseType: 'blob', // 重要：指定响应类型为 blob
    });

    // 获取文件名
    let filename = `document_${fileId}`;
    const contentDisposition = response.headers['content-disposition'];
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename=["']?([^"']+)["']?/);
      if (filenameMatch && filenameMatch[1]) {
        filename = filenameMatch[1];
      }
    }

    // 创建Blob URL并下载
    const blob = new Blob([response.data]);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    link.click();
    // 清理
    window.URL.revokeObjectURL(url);
  } catch (error) {
    // 处理错误响应
    if (error.response && error.response.data instanceof Blob) {
      // 如果错误响应也是blob，需要读取它
      const reader = new FileReader();
      reader.onload = () => {
        const errorData = JSON.parse(reader.result);
        console.error('下载失败:', errorData.message);
      };
      reader.readAsText(error.response.data);
    } else {
      console.error('下载请求失败:', error);
    }
  }
};
</script>

<style scoped lang="scss">
.knowledge-container {
  padding: 20px;
  background-color: #fff;
  margin: 10px;
}
.knowledge-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}
</style>
